package com.ecarx.module_udisk;

import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ecarx.library_base.base_fragment.BaseFragment;
import com.ecarx.library_base.base_util.ThreadUtils;
import com.ecarx.library_base.base_view.ThemeTextView;
import com.ecarx.library_base.base_widget.ConfirmDialog;
import com.ecarx.library_base.usb.UDiskManager;
import com.ecarx.module_udisk.adapter.LogAdapter;
import com.ecarx.module_udisk.adapter.PathAdapter;
import com.ecarx.module_udisk.adapter.UdiskPathAdapter;
import com.ecarx.module_udisk.bean.LogBean;
import com.ecarx.module_udisk.bean.PathBean;
import com.ecarx.module_udisk.callback.ImgUpdateCallback;
import com.ecarx.module_udisk.controller.ImgUpdateController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class UDiskPartitionUpdateFragment extends BaseFragment {

    //系统选择
    private Spinner mSpinner;
    // 日志列表
    private RecyclerView mLogRecyclerView;
    private LogAdapter mLogAdapter;
    // 文件路径列表
    private RecyclerView mPathRecyclerView;
    private UdiskPathAdapter mPathAdapter;
    //全选按钮
    private CheckBox mPathAllSelectCheckBox;
    private final String noticePath = "usb_upgrade/img_update/";
    private String[] systemTag = {"Uxos", "ClusterOS", "GameOS"};
    // 当前选择的系统
    private String curSelectSystem = "Uxos";
    private TextView tvTitleFileSelect;
    private TextView tvTitleFileSelectDetail;
    private TextView tvTitleSystemSelectDetail;
    private TextView tvTitleLog;
    private ThemeTextView mThemeTextView;
    private TextView tvUDiskName;
    private ImgUpdateController mImgUpdateController;

    public UDiskPartitionUpdateFragment() {
        // Required empty public constructor
    }

    @Override
    protected int layoutId() {
        return R.layout.fragment_u_disk_common_update;
    }

    @Override
    protected void init(View view) {
        initView(view);
        initData();
        mImgUpdateController = new ImgUpdateController(getActivity(), new ImgUpdateCallback() {
            @Override
            public void imgUpdateLog(List<LogBean> logList) {
                ThreadUtils.runOnUiThread(() -> {
                    if (mLogAdapter != null) {
                        mLogAdapter.setLogList(logList);
                        mLogRecyclerView.scrollToPosition(mLogAdapter.getItemCount() - 1);
                    }
                });
            }

            @Override
            public void setUDiskInfo(String fsLabel) {
                tvUDiskName.setText(fsLabel);
            }

            @Override
            public void setPathBeanList(List<PathBean> pathBeanList) {
                ThreadUtils.runOnUiThread(() -> {
                    if (!isAdded()) {
                        return;
                    }
                    if (mPathAdapter != null) {
                        mPathAdapter.setPathList(pathBeanList);
                    }

                });
            }

            @Override
            public void imgUpdateLogEnd() {
                ThreadUtils.runOnUiThread(() -> {
                    if (!isAdded()) {
                        return;
                    }
                    clearLoading();
                    mThemeTextView.setEnabled(true);
                });
            }
        });
    }

    private void initData() {
        initSpinnerData();
        initUpdateLogData();
        initDiskPath();
    }

    //初始化 U盘路径
    private void initDiskPath() {
        List<PathBean> pathList = new ArrayList<>();
        mPathAdapter = new UdiskPathAdapter(getActivity());
        mPathRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        mPathRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mPathRecyclerView.setAdapter(mPathAdapter);
        mPathAdapter.setPathList(pathList);

    }

    //初始化升级日志
    private void initUpdateLogData() {
        mLogAdapter = new LogAdapter(getActivity());
        mLogRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mLogRecyclerView.setAdapter(mLogAdapter);

    }

    //初始化Spinner
    private void initSpinnerData() {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, Arrays.asList(systemTag)) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                TextView tv = (TextView) super.getView(position, convertView, parent);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
                return tv;
            }
        };
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
        mSpinner.post(() -> mSpinner.setDropDownVerticalOffset(mSpinner.getHeight()));
        mSpinner.setAdapter(adapter);
        int select  = Arrays.asList(systemTag).indexOf(curSelectSystem);
        mSpinner.setSelection(select);
        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                curSelectSystem = systemTag[position];
                String string = getString(R.string.part_file_select_detail);
                tvTitleFileSelectDetail.setText(string + noticePath + curSelectSystem);
                mImgUpdateController.setCurSelectSystem(curSelectSystem);
                mImgUpdateController.dealDeviceInfo(UDiskManager.getInstance().getAllUDiskDevice());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void initView(View view) {
        mSpinner = view.findViewById(R.id.spinner_system_choose);
        mLogRecyclerView = view.findViewById(R.id.log_recycler);
        mPathRecyclerView = view.findViewById(R.id.file_path_recycler);
        mPathAllSelectCheckBox = view.findViewById(R.id.cb_check);

        tvUDiskName = view.findViewById(R.id.title_udisk_name_detail);
        //title init
        tvTitleSystemSelectDetail = view.findViewById(R.id.title_system_select_detail);
        tvTitleSystemSelectDetail.setText(R.string.part_system_select_detail);
        tvTitleLog = view.findViewById(R.id.title_log);
        tvTitleLog.setText(R.string.part_update_log);
        tvTitleFileSelect = view.findViewById(R.id.title_file_select);
        tvTitleFileSelect.setText(R.string.part_file_select);
        tvTitleFileSelectDetail = view.findViewById(R.id.title_file_select_detail);
        String string = getString(R.string.part_file_select_detail);
        tvTitleFileSelectDetail.setText(string + noticePath + curSelectSystem);
        mThemeTextView = view.findViewById(R.id.btn_update);
        mThemeTextView.setText(R.string.part_start_update);
        mThemeTextView.setEnabled(false);
        mPathAllSelectCheckBox.setVisibility(View.GONE);
        mThemeTextView.setOnClickListener(view1 -> {
            ConfirmDialog confirmDialog = new ConfirmDialog(getActivity(), context.getString(R.string.img_update_notice), () -> {
                showLoading();
                ThreadUtils.getCachedPool().execute(() -> {
                    mImgUpdateController.imgStartUpload(mPathAdapter.getCheckPath());
                });
            });
            if (!confirmDialog.isShowing()) {
                confirmDialog.show();
            }
        });
    }
}